package com.bingxue.edu.management.shop.service;

import com.bingxue.edu.common.enums.CommonStatusEnum;
import com.bingxue.edu.framework.common.model.PageQuery;
import com.bingxue.edu.framework.common.util.ValidationUtils;
import com.bingxue.edu.framework.mybatis.base.BaseService;
import com.bingxue.edu.framework.mybatis.query.QueryBuilder;
import com.bingxue.edu.management.shop.mapper.CouponTemplateMapper;
import com.bingxue.edu.management.shop.model.entity.CouponTemplate;
import com.bingxue.edu.management.shop.model.query.CouponTemplateQuery;
import com.bingxue.edu.management.shop.model.req.CouponTemplateReq;
import com.bingxue.edu.management.shop.model.resp.CouponTemplateResp;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import static com.bingxue.edu.management.shop.model.entity.table.CouponTemplateTableDef.COUPON_TEMPLATE;

/**
 * 优惠卷模板业务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CouponTemplateService extends BaseService<CouponTemplateMapper, CouponTemplate> {

    @Transactional(rollbackFor = Exception.class)
    public void create(CouponTemplateReq req) {
        CouponTemplate couponTemplate = this.copy(req);
        if (req.getSingleClassIdLimit() != null) {
            couponTemplate.setClassIdLimit(List.of(req.getSingleClassIdLimit()));
        }
        couponTemplate.setReceivedCount(0);
        couponTemplate.setUsedCount(0);
        this.save(couponTemplate);
        log.info("创建优惠卷成功, {}", couponTemplate);
    }

    public Page<CouponTemplateResp> queryPage(CouponTemplateQuery query, PageQuery pageQuery) {
        QueryWrapper queryWrapper = QueryBuilder.build(query, pageQuery);
        return this.pageAs(pageQuery.toPage(), queryWrapper, CouponTemplateResp.class);
    }

    public void deleteById(String id) {
        //如果优惠券被领用过，无法删除
        CouponTemplate couponTemplate = this.getById(id);
        ValidationUtils.throwIfNull(couponTemplate,"优惠券不存在");
        ValidationUtils.throwIf(couponTemplate.getReceivedCount() > 0,"已存在优惠券领用记录，无法删除");
        this.getMapper().deleteById(id);
    }

    public CouponTemplate getDetailById(String id) {
        return this.queryChain().where(COUPON_TEMPLATE.ID.eq(id)).one();
    }

    /**
     * 增加优惠券模板使用数量
     * @param couponTemplateId 优惠券模板id
     */
    @Transactional(rollbackFor = Exception.class)
    public void increaseUsedCount(String couponTemplateId, Integer num) {
        this.updateChain().where(COUPON_TEMPLATE.ID.eq(couponTemplateId))
                .set(COUPON_TEMPLATE.USED_COUNT, COUPON_TEMPLATE.USED_COUNT.add(num))
                .update();
    }

    /**
     * 增加优惠券模板使用数量
     * @param couponTemplateId 优惠券模板id
     */
    @Transactional(rollbackFor = Exception.class)
    public void increaseReceivedCount(String couponTemplateId, Integer num) {
        this.updateChain().where(COUPON_TEMPLATE.ID.eq(couponTemplateId))
                .set(COUPON_TEMPLATE.RECEIVED_COUNT, COUPON_TEMPLATE.RECEIVED_COUNT.add(num))
                .update();
    }

    /**
     * 校验班级状态
     */
    public void checkCouponTemplateStatus(CouponTemplate couponTemplate) {
        ValidationUtils.throwIfNull(couponTemplate, "优惠券不存在");
        ValidationUtils.throwIf(CommonStatusEnum.ENABLED != couponTemplate.getStatus(), "优惠券不可用");
    }

    /**
     * 优惠卷模板发放数量减一
     * @param couponTemplateId 优惠卷模板数量
     */
    public void decreaseDistributedCount(String couponTemplateId) {
        this.updateChain().set(COUPON_TEMPLATE.DISTRIBUTED_COUNT,COUPON_TEMPLATE.DISTRIBUTED_COUNT.add(-1))
                .where(COUPON_TEMPLATE.ID.eq(couponTemplateId))
                .update();
    }
}
